#!/usr/bin/perl
# Post the monthly counter report to comp.os.linux.misc
# Uses the Per5 "NNTP" module.

use News::NNTPClient;
use Net::SMTP;

# Set some configs
$dir = "/home/counter";
$dir = $ENV{COUNTER_ROOT} if $ENV{COUNTER_ROOT};
$report = "reports/short.txt";
$intro = "data/intro.txt";
# News config
$newsgroup = "comp.os.linux.misc";
$newsserver = "nntp-trd.uninett.no";
# Mail config
$mailhost = "localhost";
$mailrecip = "announce\@counter.li.org";

chdir($dir) || die "Could not change to $dir\n";
# Check command line options
while ($ARGV[0] =~ /^-/) {
    $opt = shift;
    if ($opt eq "-m") {
	$mailonly = 1;
    } elsif ($opt eq "-n") {
	$postonly = 1;
    } elsif ($opt eq "-t") {
	$testonly = 1;
    }
}


open(REPORT, $report) || die "Could not open $report\n";
@report = <REPORT>;
close REPORT;

@users = grep(/persons register/, @report);
if ($users[0] =~ /There are (\d+) persons register/) {
    $users = $1;
} else {
    die "Could not find usercount in $report\n";
    print @users, @report, "\n";
}
open(INTRO, $intro) || die "Intro not found\n";
@intro = <INTRO>;
close INTRO;

if ($testonly) {
    print "This is the report\n\n";

    for $line (@intro) {
	print $line;
    }
    for $line (@report) {
	print $line;
    }
    exit(0);
}

if (!$mailonly) {
    @header = (
	       "From: Harald\@alvestrand.no",
	       "Newsgroups: $newsgroup",
	       "Subject: Linux Counter: $users registered Linux users",
	       "Organization: Alvestrand Data"
	       );
    
    $c = new News::NNTPClient($newsserver);
    if (!$c -> ok) {
	die "Something wrong on init\n";
    }
    
# Post as news
    $c -> group("no.test");
    if (! $c -> postok) {
	die "Not allowed to post\n";
    }
    
    $c -> post(@header, "", @intro, @report);
    $msg = $c -> message;
    print "Post returned $msg\n";
}

# Send as mail
if (!$postonly) {
    $smtp = Net::SMTP->new($mailhost)
	|| die "Unable to connect to $mailhost\n";

    $smtp->mail("reports\@counter.li.org") || die "Unable to mail\n";
    $smtp->to($mailrecip) || die "Unable to RCPT TO\n";

    $smtp->data() || die "Unable to DATA\n";
    $smtp->datasend("From: reports\@counter.li.org\n");
    $smtp->datasend("To: $mailrecip\n");
    $smtp->datasend("Subject: Linux Counter: $users registered Linux users\n");
    $smtp->datasend("\n");
    for $line (@report) {
	$smtp->datasend($line);
    }
    $smtp->dataend() || die "Unable to dataend\n";

    $smtp->quit;
    print "Email sent\n";
}




